import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)//把VueRouter (路由添加到vue实例里面)


const routes = [
  //定义一个路由规则
  {
    path: '/',//home 界面路由规则
    component: () => import('@/views/layout'),
    redirect: '/home',
    // home界面里面的子路由规则
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'user-info',//重置信息路由
        component: () => import('@/views/user/userInfo.vue')
      },
      {
        path: 'user-avatar',//更换头像路由
        component: () => import('@/views/user/userAvatar.vue')
      },
      {
        path: 'user-pwd', //重置密码路由
        component: () => import('@/views/user/userPwd.vue')
      },
      {
        path: 'art-cate',//
        component: () => import('@/views/article/artCate.vue')
      },
      {
        path: 'art-list', // 文章列表
        component: () => import('@/views/article/artList')
      },
    ]
  },
  {//
    path: '/login',//注册界面路由
    component: () => import('@/views/login')
  },
  {//
    path: '/register',//登录界面路由
    component: () => import('@/views/register')
  },
  // { 
  //   path: '/login',
  //   component: () => import('@/views/login')
  // },
]
const whiteList = ['/login', '/register'] //设置白名单数组
const router = new VueRouter({ //new 一个路由 routes(上面定义好规则的路由) 
  routes
})
router.beforeEach((to, from, next) => { //路由守卫
  const token = store.state.token //用户有token 赋值到当前页面
  if (token) {
    // 如果有token, 证明已登录
    if (!store.state.userInfo.username) {
      // 有token但是没有用户信息, 才去请求用户信息保存到vuex里
      // 调用actions里方法请求数据
      store.dispatch('getUserInfoActions')
      // 下次切换页面vuex里有用户信息数据就不会重复请求用户信息
    }
    next()// 路由放行
  } else {
    // 如果无token
    // 如果去的是白名单页面, 则放行
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 如果其他页面请强制拦截并跳转到登录页面
      next('/login')
    }
  }

});

export default router//导出路由
